package com.genokon.druid.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.genokon.druid.entity.GeneOmiEntry;
import com.genokon.druid.mapper.GeneOmiMapper;
import com.genokon.druid.service.OmiService;
import com.genokon.druid.service.RequestOmiDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author by baichaoda
 * @date 2020/9/29 10:30
 */
@Service("omiService")
@Slf4j
public class OmiServiceImpl implements OmiService {
    @Resource
    private RequestOmiDataService requestOmiDataService;
    @Resource
    GeneOmiMapper geneOmiMapper;

    @Override
    public String downloadDatabase(String auth) {
        ExecutorService executorService = new ThreadPoolExecutor(1, 1,
                0, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(512),
                new ThreadPoolExecutor.DiscardPolicy());
        executorService.execute(new DownLoadThreadOmi(auth));
        return "success";
    }

    public class DownLoadThreadOmi implements Runnable{
        private Pattern pattern = Pattern.compile("HP:\\d{7}");
        private final String auth;
        DownLoadThreadOmi(String auth){
            this.auth = auth;
        }

        @Override
        public void run() {
            int page = 1;
            while (true){
                String rs = requestOmiDataService.getOmi(this.auth, page);
                JSONObject rsObject = JSONObject.parseObject(rs);
                JSONArray results = rsObject.getJSONArray("results");

                for (int i = 0; i < results.size(); i++){
                    JSONObject object = results.getJSONObject(i);
                    //重复数据
                    String nimNo = object.getString("mimNumber");
                    geneOmiMapper.delete(new QueryWrapper<GeneOmiEntry>().lambda().eq(GeneOmiEntry::getMimNumber, nimNo));

                    GeneOmiEntry entry = new GeneOmiEntry();
                    entry.setMimNumber(nimNo);
                    entry.setPrefix(object.getString("prefix"));
                    entry.setType(1);
                    String preTitle = object.getString("preTitle");
                    String[] str = preTitle.split(";\\s*");
                    if (str.length == 0){
                        continue;
                    }

                    if (str.length > 1){
                        entry.setTitleEn(str[0]);
                        entry.setAbbreviate(str[1]);
                    }else {
                        entry.setTitleEn(str[0]);
                    }
                    entry.setTitleCn(object.getString("cnTitle"));
                    geneOmiMapper.insert(entry);


                    //分析别名
                    String altTitle = object.getString("altTitle");
                    if (StringUtils.isEmpty(altTitle)){
                        continue;
                    }

                    String[] altTitles = altTitle.split(";;\\s*");
                    for (String alt: altTitles){
                        entry.setId(null);
                        entry.setCreateTime(null);
                        entry.setType(0);
                        entry.setTitleCn(null);
                        entry.setAbbreviate(null);
                        entry.setTitleEn(alt);
                        geneOmiMapper.insert(entry);
                    }
                    //handleRelateOmiHop(nimNo, object.getJSONArray("Omim_HPO"));

                }

                log.info("==========complete=======" + page + "=====page=========");


                if (results.size() < 20){
                    break;
                }
                page++;
            }
            log.info("==========complete=======success=========");
        }

        private void handleRelateOmiHop(String omi, JSONArray array){
            for (int i = 0; i < array.size(); i++){
                String relHpo = array.getString(i);
                Matcher m = pattern.matcher(relHpo);
                if (m.find()){
                    String hpo = m.group();
                    if (StringUtils.isEmpty(geneOmiMapper.getRelOfHpoOmi(omi, hpo))){
                        geneOmiMapper.insertHpoAndOmi(omi, hpo);
                    }
                }
            }

        }
    }
}
